<template>
  <el-dialog
    v-model="visible"
    title="同步历史"
    width="1200px"
    @close="handleClose"
  >
    <div class="sync-history-content">
      <!-- 搜索区域 -->
      <!-- <el-card shadow="never" style="margin-bottom: 16px">
        <div class="search-form-container">
          <DynamicForm
            ref="searchFormRef"
            v-model="searchForm"
            :form-config="searchFormConfig"
            :gutter="16"
            label-width="100px"
            type="search"
            @search="handleSearch"
            @reset="handleReset"
          />
        </div>
      </el-card> -->

      <!-- 表格区域 -->
      <DynamicTable
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        border
        stripe
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #action="{ row }">
          <el-button
            type="primary"
            link
            size="small"
            @click="handleViewDetail(row)"
          >
            查看
          </el-button>
          <el-button type="danger" link size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </DynamicTable>
    </div>

    <!-- 比对结果弹窗 -->
    <SyncComparisonDialog
      v-model="showComparisonDialog"
      :run-id="comparisonRunId"
      :task-name="comparisonTaskName"
      :sync-time="comparisonSyncTime"
      @close="showComparisonDialog = false"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, h } from "vue";
import { querySyncHistory } from "@/api/task";
import { ElMessage, ElMessageBox, ElTag } from "element-plus";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import SyncComparisonDialog from "./SyncComparisonDialog.vue";

interface Props {
  modelValue: boolean;
  taskId: number;
  taskName: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  taskId: 0,
  taskName: "",
});

const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  close: [];
  "view-detail": [runId: string];
}>();

const visible = ref(false);
const loading = ref(false);
const tableData = ref<any[]>([]);
const searchFormRef = ref<DynamicFormInstance>();

// 比对结果弹窗相关
const showComparisonDialog = ref(false);
const comparisonRunId = ref("");
const comparisonTaskName = ref("");
const comparisonSyncTime = ref("");

const searchForm = reactive({
  dateRange: null as [string, string] | null,
});

const searchFormConfig: FormItemConfig[] = [
  {
    key: "dateRange",
    name: "时间范围",
    type: "date",
    placeholder: "请选择时间范围",
    col: {
      span: 8,
    },
    params: {
      clearable: true,
      type: "daterange",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      rangeSeparator: "~",
      startPlaceholder: "开始日期",
      endPlaceholder: "结束日期",
    },
  },
];

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

const columns = ref<TableColumn[]>([
  {
    label: "同步时间",
    prop: "run_time",
    show: true,
    align: "center",
  },
  {
    label: "记录数",
    prop: "total_count",
    show: true,
    align: "center",
    render: (row) => {
      const total =
        (row.remote_open_count || 0) +
        (row.out_of_range_count || 0) +
        (row.both_missing_count || 0) +
        (row.local_only_count || 0) +
        (row.normal_count || 0);
      return total;
    },
  },
  {
    label: "远程异常",
    prop: "remote_open_count",
    show: true,
    align: "center",
    render: (row) => {
      return h(
        ElTag,
        { type: "danger", size: "small" },
        () => row.remote_open_count || 0
      );
    },
  },
  {
    label: "超范围",
    prop: "out_of_range_count",
    show: true,
    align: "center",
    render: (row) => {
      return h(
        ElTag,
        { type: "warning", size: "small" },
        () => row.out_of_range_count || 0
      );
    },
  },
  {
    label: "双端丢失",
    prop: "both_missing_count",
    show: true,
    align: "center",
    render: (row) => {
      return h(
        ElTag,
        { type: "info", size: "small" },
        () => row.both_missing_count || 0
      );
    },
  },
  {
    label: "仅本地",
    prop: "local_only_count",

    show: true,
    align: "center",
    render: (row) => {
      return h(ElTag, { size: "small" }, () => row.local_only_count || 0);
    },
  },
  {
    label: "正常",
    prop: "normal_count",
    width: 100,
    show: true,
    align: "center",
    render: (row) => {
      return h(
        ElTag,
        { type: "success", size: "small" },
        () => row.normal_count || 0
      );
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 180,
    show: true,
    align: "center",
    fixed: "right",
    slot: "action",
  },
]);

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal) {
      loadSyncHistory();
    }
  }
);

// 监听 visible 变化，同步到父组件
watch(visible, (newVal) => {
  if (!newVal) {
    emit("update:modelValue", false);
    emit("close");
  }
});

// 加载同步历史
const loadSyncHistory = async () => {
  if (!props.taskId) {
    ElMessage.warning("任务ID不存在");
    return;
  }

  loading.value = true;
  try {
    const params: any = {
      task_id: props.taskId,
      page: pagination.currentPage,
      per_page: pagination.pageSize,
    };

    // 如果有日期范围，添加到参数中
    if (
      searchForm.dateRange &&
      Array.isArray(searchForm.dateRange) &&
      searchForm.dateRange.length === 2
    ) {
      params.start_date = searchForm.dateRange[0];
      params.end_date = searchForm.dateRange[1];
    }

    const { data } = await querySyncHistory(params);

    tableData.value = data.records || [];
    pagination.total = data.total || 0;
  } catch (error: any) {
    console.error("查询同步历史失败:", error);
    ElMessage.error("查询同步历史失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = (value: any) => {
  searchForm.dateRange =
    value.dateRange &&
    Array.isArray(value.dateRange) &&
    value.dateRange.length === 2
      ? value.dateRange
      : null;
  pagination.currentPage = 1;
  loadSyncHistory();
};

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields();
  searchForm.dateRange = null;
  pagination.currentPage = 1;
  loadSyncHistory();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadSyncHistory();
};

// 页码变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  loadSyncHistory();
};

// 查看详情
const handleViewDetail = (row: any) => {
  if (row.run_id) {
    comparisonRunId.value = row.run_id;
    comparisonTaskName.value = props.taskName;
    comparisonSyncTime.value = row.sync_time || "";
    showComparisonDialog.value = true;
  } else {
    ElMessage.warning("run_id不存在");
  }
};

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定要删除这条同步历史记录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // TODO: 调用删除接口
      ElMessage.success("删除成功");
      loadSyncHistory();
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
};
</script>

<style lang="scss" scoped>
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
</style>
